<?php
namespace Api\Service;

/**
 * 银行卡
 */
class BankcardService
{
    /**
     * 银行卡列表
     * @param  [type] $user_id [description]
     * @return [type]          [description]
     */
    public function lists($user_id)
    {
        $cards = M('bank_card')
            ->field('id,name,number,type')
            ->where([
                'user_id'   => $user_id,
                'is_delete' => 0,
            ])
            ->order('id desc')
            ->select();

        return $cards ? $cards : [];
    }

    /**
     * 添加银行卡
     * @param [type] $user_id [description]
     * @param [type] $add     [description]
     */
    public function add($user_id, $card)
    {
        $is_exist = $this->exist($card['number']);

        if ($is_exist) {
            return false;
        }

        if (!$card['name'] || !$card['number']) {
            return false;
        }

        $card['user_id']  = $user_id;
        $card['add_time'] = CUR_DATETIME;
        $res              = M('bank_card')->add($card);

        return $res;
    }

    /**
     * 删除银行卡
     * @param  [type] $user_id [description]
     * @param  [type] $card_id  [description]
     * @return [type]          [description]
     */
    public function delete($user_id, $card_id)
    {
        $data = [
            'is_delete'   => 1,
            'delete_time' => CUR_DATETIME,
        ];
        $res = M('bank_card')->where([
            'id'        => $card_id,
            'user_id'   => $user_id,
            'is_delete' => 0,
        ])->save($data);

        return $res;
    }

    /**
     * 银行卡是否已存在
     * @param  [type] $number [description]
     * @return [type]         [description]
     */
    public function exist($number)
    {
        return M('bank_card')->where(['number' => $number])->count();
    }
}
